#include "EventLoop.h"
#include "Log.h"
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <pthread.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <timewheel.h>
#include <unistd.h>
#include <Any.hpp>
#include <buffer.h>
#include <Sock.h>
#include <Poller.h>
#include <unordered_map>
#include <utility>
#include <vector>
#include <Connection.h>
#include <Acceptor.h>
#include <LoopThread.h>
#include <LoopThreadPool.h>
#include <TcpServer.h>


using namespace std;
using namespace muduo;

/* timewheel-test
class Task
{
public:
    Task()
    {
        cout << "构造函数" << endl;
    }
    ~Task()
    {
        cout << "析构函数" << endl;
    }
};

void Delete(Task* p)
{
    delete p;
}
    ==main==
    Task* p(new Task);
    muduo::TimerWheel tw;

    tw.AddTimerTask(1,5,bind(Delete,p));

    for(int i=0;i<5;i++)
    {
        sleep(1);
        tw.TimerRefresh(1);
        cout << "刷新了定时器" << endl;
    }
    // tw.TimerCancel(1);
    while (1) {
        sleep(1);
        cout << "=========" << endl;
        tw.RunTimeTask();
    }
*/
/* Any-test
class Test{
public:
    Test()
    {
        cout << "构造函数"<<endl;
    }
    Test(const Test& t)
    {
        cout << "拷贝构造函数"<<endl;
    }
    ~Test()
    {
        cout << "析构函数"<<endl;
    }
};
*/
/*
    buffer-test
    // std::string str("nihao");
    // Buffer buf ;
    // buf.WriteAsStringAndPush(str);
    // std::string str1 = buf.ReadAsStringAndPop(str.size());
    // cout << str1 <<endl; //nihao
    // Buffer buf1;

    // std::string str3(" lyt");
    // buf.WriteAsStringAndPush(str);
    // buf.WriteAsStringAndPush(str3);
    // buf1.WriteAsBufferAndPush(buf);
    // std::string str2 = buf1.ReadAsStringAndPop(str.size()+str3.size());
    // cout << str2 <<endl; //nihao lyt

    // 扩容测试
    Buffer buf;
    for(int i=0;i<100;i++)
    {
        string str = "hello" + to_string(i)+'\n';
        buf.WriteAsStringAndPush(str);
    }
    string tmp;
    for(int i=0;i<101;i++)
    {
        tmp = buf.GetLineAndPop();
        cout << tmp;
    }
*/

void message_callback(const PtrConnection& con,Buffer* buf){
    // 读取缓冲区内容
    infolog<< buf->GetReadIndex();
    // 将读指针向后偏移
    buf->MoveReadidx(buf->EnableReadSize());
    // 调用con的Send将数据发送
    std::string str = "Hello world";
    con->Send(str.c_str(),str.size());
    // con->Shutdown();
}
void connect_callback(const PtrConnection& con){
    infolog<<con->Id()<<": Connected";
}
void close_callback(const PtrConnection& con){
    infolog<<con->Id()<<": Closed";
}
int main()
{
    infolog;
    TcpServer tcpserver(38080);
    tcpserver.SetPoolNum(3);
    tcpserver.SetConnectedCallback(connect_callback);
    tcpserver.SetMessageCallback(message_callback);
    tcpserver.SetCloseCallback(close_callback);
    tcpserver.SetInactiveRelease(3);
    tcpserver.start();
    return 0;
}